package com.yuanjun.product.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuanjun.product.vo.base.BaseResult;
import com.yuanjun.product.vo.common.Const;
import com.yuanjuntech.modules.notify.interfaces.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping(value = "/sms")
public class SmsController {

    @Value("${spring.profiles.active}")
    private String env;
    @Value("${send_verification_code}")
    private int VERIFICATIONCODE;
    @Reference(version = "1.0.0")
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/send")
    public BaseResult sendSms(@RequestParam String mobile) {
        if ("release".equals(env)) {
            String poneToken = Const.ORDER_PREFIX + "-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis();
            String testCode = smsService.sendPhoneAuthCode(mobile, poneToken, VERIFICATIONCODE, null);
            log.info("发送的短信验证码是：{}", testCode);
            stringRedisTemplate.opsForValue().set("ins-sms" + mobile, testCode, 5 * 60L, TimeUnit.SECONDS);
            return BaseResult.createOk("");
        }
        String randomNumCode = randomNumCode(4);
        log.info("测试验证码：{}", randomNumCode);
        stringRedisTemplate.opsForValue().set("jcz-sms" + mobile, randomNumCode, 5 * 60L, TimeUnit.SECONDS);
        return BaseResult.createOk(randomNumCode);
    }

    private static String randomNumCode(int length) {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append((new Random().nextInt(10)));
        }
        return code.toString();
    }
}
